package cn.lx.feature;

import org.aopalliance.intercept.ConstructorInterceptor;
import org.aopalliance.intercept.MethodInterceptor;
import org.glassfish.hk2.api.Filter;
import org.glassfish.hk2.api.InterceptionService;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by Administrator on 2017/3/14.
 */
public class LxMethodInteceptorRegesiter implements InterceptionService {
    public Filter getDescriptorFilter() {
        return null;
    }

    private static Map<Class,List<MethodInterceptor>> map = new HashMap<Class,List<MethodInterceptor>>();
    public static void regeister(Class clazz ,MethodInterceptor methodInterceptor){
        List<MethodInterceptor> methodInterceptors = map.get(clazz);
        if(methodInterceptors == null || methodInterceptors.size() == 0 ){
            methodInterceptors = new ArrayList<MethodInterceptor>();

        }
        methodInterceptors.add(methodInterceptor);
        map.put(clazz,methodInterceptors);
    }

    public List<MethodInterceptor> getMethodInterceptors(Annotation[] annotations){

        Set<MethodInterceptor> set = new HashSet<MethodInterceptor>();
        if(annotations != null){
            for (Annotation annotation : annotations){
                set.addAll(getMethodInterceptors(annotation.annotationType()));
            }
        }
        return  new ArrayList<MethodInterceptor>(set);
    }
    public List<MethodInterceptor> getMethodInterceptors(Class annotations){
        List<MethodInterceptor> methodInterceptors = map.get(annotations);
        if (methodInterceptors == null){
            methodInterceptors = new ArrayList<MethodInterceptor>();
        }
        return  methodInterceptors;
    }
    //根据方法，获取对应的拦截器
    public List<MethodInterceptor> getMethodInterceptors(Method method) {

        Class<?> clazz = method.getDeclaringClass();
        if(!clazz.isAnnotationPresent(LxAOP.class) || MethodInterceptor.class.isAssignableFrom(clazz)){
            return  null;
        }
        Annotation[] annotations = method.getAnnotations();
        return getMethodInterceptors(annotations);
    }

    public List<ConstructorInterceptor> getConstructorInterceptors(Constructor<?> constructor) {
        return null;
    }
}
